﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Data;
using System.IO;
using System.Drawing.Imaging;
using System.Drawing;
using System.Drawing.Drawing2D;

public partial class Controls_ImagesByAlbum : System.Web.UI.UserControl
{
    public static string albumid = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.QueryString["aid"] != null)
            {
                albumid = Request.QueryString["aid"];
                bindAlbum();
            }
            if (string.IsNullOrEmpty(albumid))
            {
                Response.Redirect(KTFrameworkCus.Globals.ApplicationPath + "webmaster/gallery/Default.aspx");
            }
            else
            {
                loadImages(albumid);
            }
        }
    }

    /// <summary>
    /// Bind tên album vào DropDownList.
    /// </summary>
    protected void bindAlbum()
    {
        ddlAlbum.Items.Clear();
        XmlDocument xmldoc1 = new XmlDocument();
        xmldoc1.Load(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath + "dms/dmsAlbums.xml"));
        XmlNodeList nodelist = xmldoc1.SelectNodes("dms/album");
        foreach (XmlNode item in nodelist)
        {
            if (item.Attributes["id"].Value != albumid)
            {
                ddlAlbum.Items.Add(new ListItem(item["title"].InnerText, item.Attributes["id"].Value));
            }
        }
        ddlAlbum.SelectedIndex = 0;
    }


    /// <summary>
    /// Load Image vào Repeater.
    /// </summary>
    /// <param name="albumidd"></param>
    protected void loadImages(string albumidd)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("id");
        dt.Columns.Add("title");
        dt.Columns.Add("description");
        dt.Columns.Add("fullimage");
        dt.Columns.Add("thumbimage");
        dt.Columns.Add("AddedDate");
        dt.Columns.Add("ModifiedDate");
        dt.Columns.Add("order", typeof(Int32));
        dt.Columns.Add("type");
        dt.Columns.Add("title_en");
        dt.Columns.Add("description_en");
        dt.Columns.Add("url");
        dt.Columns.Add("active");
        XmlDocument xmldoc1 = new XmlDocument();
        xmldoc1.Load(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath + "dms/dmsImages.xml"));
        XmlNodeList nodelist = xmldoc1.SelectNodes("dms/image[@albumid='" + albumidd + "']");
        if (nodelist.Count > 0)
        {
            foreach (XmlNode item in nodelist)
            {
                DataRow dr = dt.NewRow();
                dr[0] = item.Attributes["id"].Value;
                dr[1] = item["title"].InnerText;
                dr[2] = item["description"].InnerText;
                dr[3] = item["fullimage"].InnerText;
                dr[4] = item["thumbimage"].InnerText;
                dr[5] = item["AddedDate"].InnerText;
                dr[6] = item["ModifiedDate"].InnerText;
                dr[7] = item["order"].InnerText;
                dr[8] = item["type"].InnerText;
                dr[9] = item["title_en"].InnerText;
                dr[10] = item["description_en"].InnerText;
                dr[11] = item["url"].InnerText;
                dr[12] = item["active"].InnerText;
                dt.Rows.Add(dr);
            }
        }

        DataTable data = new DataTable();
        DataTable tblEmployees = dt;
        DataView dv = tblEmployees.DefaultView;
        dv.Sort = "order ASC";
        data = dv.ToTable();

        dtlImages.DataSource = data;
        dtlImages.DataBind();

    }

    protected void lnkEdit_Command(object sender, CommandEventArgs e)
    {
        //    int ID = int.Parse(e.CommandArgument.ToString());
        //    XmlDocument xmldoc1 = new XmlDocument();
        //    xmldoc1.Load(Server.MapPath("~/dms/dmsAlbums.xml"));
        //    XmlNodeList nodelist = xmldoc1.SelectNodes("dms/album");
        //    XmlNode xNode = xmldoc1.SelectSingleNode("dms/album[@id='" + ID + "']");
        //    if (xNode != null)
        //    {
        //        Image1.ImageUrl = "/dms/Albums/" + xNode["poster"].InnerText;
        //        txtmota.Text = xNode["description"].InnerText;
        //        txttenalbum.Text = xNode["title"].InnerText;
        //        btnAddAlbum.CommandName = "edit";
        //        btnAddAlbum.CommandArgument = ID.ToString();
        //        btnAddAlbum.Text = "Cập nhập";
        //        btnCancel.Visible = true;
        //    }

        //LoadSupporterDetails(ID);
    }

    protected void lnkDelete_Command(object sender, CommandEventArgs e)
    {
        //int ID = int.Parse(e.CommandArgument.ToString());
        //XmlDocument xmldoc1 = new XmlDocument();
        //xmldoc1.Load(Server.MapPath("~/dms/dmsAlbums.xml"));
        //XmlNode xNode = xmldoc1.SelectSingleNode("dms/album[@id='" + ID + "']");
        //if (xNode != null)
        //{
        //    XmlDocument xmldoc = new XmlDocument();
        //    xmldoc.Load(Server.MapPath("~/dms/dmsImages.xml"));
        //    XmlNodeList nodelist = xmldoc.SelectNodes("dms/image[@albumid='" + ID + "']");
        //    if (nodelist.Count > 0)
        //    {
        //        foreach (XmlNode item in nodelist)
        //        {
        //            item.ParentNode.RemoveChild(item);
        //            xmldoc.Save(Server.MapPath("~/dms/dmsImages.xml"));
        //        }
        //    }
        //    xNode.ParentNode.RemoveChild(xNode);
        //    xmldoc1.Save(Server.MapPath("~/dms/dmsAlbums.xml"));
        //    LoadAlbum();
        //}
        //LoadSupporterDetails(ID);
    }

    //protected void dtlImages_OnItemDataBound(object sender, RepeaterItemEventArgs e)
    //{
    //    DataTable dt = new DataTable();
    //    dt.Columns.Add("id");
    //    dt.Columns.Add("title");
    //    dt.Columns.Add("description");
    //    dt.Columns.Add("fullimage");
    //    dt.Columns.Add("thumbimage");
    //    dt.Columns.Add("AddedDate");
    //    dt.Columns.Add("ModifiedDate");
    //    dt.Columns.Add("order", typeof(Int32));
    //    dt.Columns.Add("type");

    //    DataRowView drv = (DataRowView)e.Item.DataItem;
    //    Repeater rptVideo = (Repeater)e.Item.FindControl("rptVideo");
    //    if (drv!=null)
    //    {
    //        if (drv[8].ToString() == "video")
    //        {
    //            DataRow dr = dt.NewRow();
    //            dr[0] = drv[0];
    //            dr[1] = drv[1];
    //            dr[2] = drv[2];
    //            dr[3] = drv[3];
    //            dr[4] = drv[4];
    //            dr[5] = drv[5];
    //            dr[6] = drv[6];
    //            dr[7] = drv[7];
    //            dr[8] = drv[8];
    //            dt.Rows.Add(dr);
    //        }
    //    }

    //    rptVideo.DataSource = dt;
    //    rptVideo.DataBind();
    //}

    public string getExtension(string filename)
    {
        string fileext = filename.Substring(filename.LastIndexOf('.') + 1).ToUpper();
        if (fileext == "mp4")
        {
            return "video/mp4";
        }
        else if (fileext == "webm")
        {
            return "video/webm";
        }
        else if (fileext == "ogv")
        {
            return "video/ogg";
        }
        else
        {
            return "video/mp4";
        }
    }
    //protected void dtlImages_OnItemDataBound(object sender, RepeaterItemEventArgs e)
    //{
    //    DataRowView _dtrw = (DataRowView)e.Item.DataItem;
    //    TextBox _title = (TextBox)e.Item.FindControl("txttenhinh");
    //    TextBox _title_en = (TextBox)e.Item.FindControl("txttenhinh_en");
    //    TextBox _des = (TextBox)e.Item.FindControl("txtmota");
    //    TextBox _des_en = (TextBox)e.Item.FindControl("txtmota_en");
    //    HiddenField _iid = (HiddenField)e.Item.FindControl("hfImageID");
    //    _title.Text = _dtrw["title"].ToString();
    //    _title_en.Text = _dtrw["description"].ToString();
    //    _des.Text = _dtrw["title_en"].ToString();
    //    _des_en.Text = _dtrw["description_en"].ToString();
    //    _iid.Value = _dtrw["id"].ToString();
    //}
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (ckChapNhan.Checked == false)
        {
            lbmess.Text = "Bạn phải chọn đồng ý thay đổi để xác nhận việc thay đổi";
            return;
        }
        string imageid = hfimageid.Value;
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.Load(Server.MapPath(Page.ResolveUrl("~/dms/dmsImages.xml")));
        XmlNode node = xmldoc.SelectSingleNode("dms/image[@id='" + imageid + "']");
        if (node != null)
        {
            if (FileUpload2.HasFile)
            {
                if (node["type"].InnerText == "video")
                {
                    string tempPath = KTFrameworkCus.Globals.ApplicationPath + "dms/Images/t";
                    string savepath = Server.MapPath(tempPath);
                    string imagename = node["thumbimage"].InnerText;
                    string filename = DateTime.Now.Ticks.ToString() + "." + FileUpload2.FileName.Substring(FileUpload2.FileName.LastIndexOf(".") + 1);
                    string newfilename = "r" + filename;
                    if (!Directory.Exists(savepath))
                        Directory.CreateDirectory(savepath);
                    FileUpload2.SaveAs(savepath + @"\" + newfilename);
                    System.Drawing.Image myImg = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(tempPath + "/" + newfilename));
                    SaveCompressed(myImg, HttpContext.Current.Server.MapPath(tempPath + "/" + filename), 100);
                    myImg.Dispose();

                    dmsFunction.deleteImage(HttpContext.Current.Server.MapPath(tempPath + "/" + newfilename));

                    node["thumbimage"].InnerText = filename;
                    xmldoc.Save(Server.MapPath(Page.ResolveUrl("~/dms/dmsImages.xml")));

                    if (imagename!="playvideo.png")
                    {
                        FileInfo TheFile = new FileInfo(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath + "dms/Images/t/" + imagename));
                        if (TheFile.Exists)
                        {
                            File.Delete(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath + "dms/Images/t/" + imagename));
                        }
                    }
                }
                else
                {
                    string tempPath = KTFrameworkCus.Globals.ApplicationPath + "dms/Images/f";
                    string savepath = Server.MapPath(tempPath);
                    string imagename = node["fullimage"].InnerText;
                    string filename = DateTime.Now.Ticks.ToString() + "." + FileUpload2.FileName.Substring(FileUpload2.FileName.LastIndexOf(".") + 1);
                    string newfilename = "r" + filename;
                    if (!Directory.Exists(savepath))
                        Directory.CreateDirectory(savepath);
                    FileUpload2.SaveAs(savepath + @"\" + newfilename);
                    System.Drawing.Image myImg = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(tempPath + "/" + newfilename));
                    SaveCompressed(myImg, HttpContext.Current.Server.MapPath(tempPath + "/" + filename), 100);
                    myImg.Dispose();

                    dmsFunction.deleteImage(HttpContext.Current.Server.MapPath(tempPath + "/" + newfilename));

                    Bitmap bmp = new Bitmap(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath + "dms/Images/f/" + filename));
                    float imgW = bmp.Width;
                    float imgH = bmp.Height;
                    float ratio = imgW / imgH;
                    int fW = 170;
                    int fH = (int)Math.Ceiling(170 / ratio);
                    if (fH < 130)
                    {
                        fH = 130;
                        fW = (int)Math.Ceiling(130 * ratio);
                    }
                    bmp.Dispose();
                    resizeImage(KTFrameworkCus.Globals.ApplicationPath + "dms/Images/f/" + filename, fW, fH, filename);

                    node["fullimage"].InnerText = filename;
                    node["thumbimage"].InnerText = filename;
                    xmldoc.Save(Server.MapPath(Page.ResolveUrl("~/dms/dmsImages.xml")));


                    FileInfo TheFile = new FileInfo(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath + "dms/Images/t/" + imagename));
                    if (TheFile.Exists)
                    {
                        File.Delete(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath + "dms/Images/t/" + imagename));
                    }

                    FileInfo TheFile1 = new FileInfo(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath + "dms/Images/f/" + imagename));
                    if (TheFile1.Exists)
                    {
                        File.Delete(Server.MapPath(KTFrameworkCus.Globals.ApplicationPath + "dms/Images/f/" + imagename));
                    }

                }
                Response.Redirect(Request.RawUrl);

            }
            else
            {
                lbmess.Text = "Vui lòng chọn file để thay đổi!";
                return;
            }
        }
        else
        {
            lbmess.Text = "Hình ảnh này không tồn tại!";
            return;
        }
    }

    private void SaveCompressed(System.Drawing.Image img, string fileName,
    long quality)
    {
        EncoderParameters parameters = new EncoderParameters(1);
        parameters.Param[0] = new EncoderParameter(Encoder.Quality, quality);
        img.Save(fileName, GetCodecInfo("image/jpeg"), parameters);
    }

    private ImageCodecInfo GetCodecInfo(string mimeType)
    {
        foreach (ImageCodecInfo encoder in ImageCodecInfo.GetImageEncoders())
            if (encoder.MimeType == mimeType)
                return encoder;
        throw new ArgumentOutOfRangeException(
            string.Format("'{0}' not supported", mimeType));
    }

    public Size OriginalImageSize { get; set; }
    public Size NewImageSize { get; set; }
    protected void resizeImage(string imageUrl, int FixedWidth, int FixedHeight, string filename)
    {
        Bitmap imgPhoto = new Bitmap(HttpContext.Current.Server.MapPath(imageUrl));
        Bitmap b = new Bitmap(FixedWidth, FixedHeight);
        Graphics g = Graphics.FromImage(b);
        g.SmoothingMode = SmoothingMode.AntiAlias;
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        g.DrawImage(imgPhoto, 0, 0, FixedWidth, FixedHeight);
        imgPhoto.Dispose();
        b.Save(HttpContext.Current.Server.MapPath(KTFrameworkCus.Globals.ApplicationPath + "dms/Images/t/" + filename), ImageFormat.Png);
        b.Dispose();

    }
}